package com.qingyun.web.controller.wxapi;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.page.PagePlus;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.core.validate.AddGroup;
import com.qingyun.common.core.validate.EditGroup;
import com.qingyun.common.exception.CustomException;
import com.qingyun.common.exception.ServiceException;
import com.qingyun.common.utils.PageUtils;
import com.qingyun.common.utils.QrcodeGeneratorUtils;
import com.qingyun.security.controller.BaseController;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokActivity;
import com.qingyun.shop.domain.TiktokActivityTag;
import com.qingyun.shop.domain.TiktokActivityToCoupon;
import com.qingyun.shop.domain.TiktokShop;
import com.qingyun.shop.domain.bo.TiktokActivityBo;
import com.qingyun.shop.domain.vo.TiktokActivityVo;
import com.qingyun.shop.mapper.TiktokActivityTagMapper;
import com.qingyun.shop.service.ITiktokActivityService;
import com.qingyun.shop.service.ITiktokActivityToCouponService;
import com.qingyun.shop.service.ITiktokCouponService;
import com.qingyun.shop.service.ITiktokShopService;
import com.qingyun.tiktok.config.DyConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "商家小程序活动管理")
@RequestMapping("/miniapp/activity")
@RestController
@AllArgsConstructor
public class ShopActivityController extends BaseController {

    private final ITiktokActivityService iTiktokActivityService;

    private final ITiktokActivityToCouponService tiktokActivityToCouponService;

    private final TiktokActivityTagMapper activityTagMapper;

    private final ITiktokShopService shopService;

	private DyConfig dyConfig;

    @ApiOperation("活动列表")
    @GetMapping("/list")
    public TableDataInfo<TiktokActivityVo> list(@Validated TiktokActivityBo bo) {
        Long shopId = SecurityUtils.getAppLoginUser().getShop().getId();
        bo.setShopId(shopId);
        PagePlus<TiktokActivity, TiktokActivityVo> result = iTiktokActivityService.pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }


	@ApiOperation("查看活动二维码")
	@GetMapping("/getActivityQrcode")
	public AjaxResult activityQrcode(Long activityId) throws UnsupportedEncodingException {
		TiktokActivityVo tiktokActivityVo = iTiktokActivityService.queryById(activityId);
		if (ObjectUtil.isNull(tiktokActivityVo)) {
			return AjaxResult.error("活动不存在");
		}
		StringBuilder builder = new StringBuilder();
		builder.append("https://open.douyin.com/platform/oauth/connect/?client_key=");
		builder.append(dyConfig.getAppId());
		builder.append("&response_type=code&scope=user_info,video.create,video.data,fans.check,item.comment&redirect_uri=");
		StringBuilder redirectUrl = new StringBuilder();
		redirectUrl.append(dyConfig.getUserRedirectUri());
		redirectUrl.append("?activityId=");
		redirectUrl.append(activityId);
		redirectUrl.append("&shopUserId=");
		redirectUrl.append(SecurityUtils.getAppLoginUser().getSysUser().getUserId());
		String encode = URLEncoder.encode(redirectUrl.toString(), "utf-8");
		builder.append(encode);
		String baseQrcodeBase64 = QrcodeGeneratorUtils.createBaseQrcodeBase64(builder.toString());
		return AjaxResult.success(baseQrcodeBase64);
	}

    @ApiOperation("活动详情")
    @GetMapping("/{id}")
    public AjaxResult<TiktokActivityVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        TiktokActivityVo tiktokActivityVo = iTiktokActivityService.getVoById(id);

        List<TiktokActivityToCoupon> list = tiktokActivityToCouponService.list(Wrappers.lambdaQuery(TiktokActivityToCoupon.class)
                .eq(TiktokActivityToCoupon::getActivityId, tiktokActivityVo.getId()));
        tiktokActivityVo.setCouponIds(list.stream().map((TiktokActivityToCoupon::getCouponId)).collect(Collectors.toList()));

        List<Long> tagIds = activityTagMapper.selectList(Wrappers.query(new TiktokActivityTag().setActivityId(id))).stream().map(TiktokActivityTag::getTagId).collect(Collectors.toList());
        tiktokActivityVo.setTags(tagIds);

        return AjaxResult.success(iTiktokActivityService.queryById(id));
    }

    @ApiOperation("新增活动")
    @RepeatSubmit()
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody TiktokActivityBo bo) {

        if (bo.getEndDate().before(bo.getBeginDate())) {
            throw new ServiceException("活动开始时间不能在结束时间后");
        }

        if (bo.getActityType().equals("0") && bo.getCouponIds().isEmpty()) {
            throw new CustomException("优惠卷不能为空");
        }

        List<Long> couponIds = bo.getCouponIds();
        TiktokActivity add = BeanUtil.toBean(bo, TiktokActivity.class);
        add.setShopId(SecurityUtils.getAppLoginUser().getShop().getId());
        TiktokShop shop = shopService.getById(add.getShopId());
        add.setShopName(shop.getName());

        if (iTiktokActivityService.save(add)) {
            couponIds.forEach(couponId -> {
                TiktokActivityToCoupon tiktokActivityToCoupon = new TiktokActivityToCoupon().setActivityId(add.getId()).setCouponId(couponId);
                tiktokActivityToCouponService.save(tiktokActivityToCoupon);
            });

            bo.getTags().forEach(t -> activityTagMapper.insert(new TiktokActivityTag().setActivityId(add.getId()).setTagId(t)));

            return AjaxResult.success("新增成功");
        }

        return AjaxResult.error("新增失败");
    }

    @ApiOperation("活动修改")
    @RepeatSubmit()
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody TiktokActivityBo bo) {
        if (bo.getEndDate().before(bo.getBeginDate())) {
            throw new ServiceException("活动开始时间不能在结束时间后");
        }

        if (bo.getActityType().equals("0") && bo.getCouponIds().isEmpty()) {
            throw new CustomException("优惠卷不能为空");
        }

        TiktokActivity update = BeanUtil.toBean(bo, TiktokActivity.class);

        List<Long> couponIds = bo.getCouponIds();

        if (iTiktokActivityService.updateById(update)) {
            //清除全部绑定的优惠卷
            tiktokActivityToCouponService
                    .remove(Wrappers.lambdaQuery(TiktokActivityToCoupon.class)
                            .eq(TiktokActivityToCoupon::getActivityId, bo.getId()));
            //添加优惠卷
            couponIds.forEach(couponId -> {
                TiktokActivityToCoupon tiktokActivityToCoupon = new TiktokActivityToCoupon().setActivityId(bo.getId()).setCouponId(couponId);
                tiktokActivityToCouponService.save(tiktokActivityToCoupon);
            });

            // 清除所有标签
            activityTagMapper.delete(Wrappers.query(new TiktokActivityTag().setActivityId(bo.getId())));
            bo.getTags().forEach(t -> {
                activityTagMapper.insert(new TiktokActivityTag().setActivityId(bo.getId()).setTagId(t));
            });


            return AjaxResult.success("修改成功");
        }

        return AjaxResult.error("修改失败");
    }

    //@ApiOperation("活动二维码")

    private LambdaQueryWrapper<TiktokActivity> buildQueryWrapper(TiktokActivityBo bo) {
        LambdaQueryWrapper<TiktokActivity> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), TiktokActivity::getTitle, bo.getTitle());
        lqw.eq(bo.getBeginDate() != null, TiktokActivity::getBeginDate, bo.getBeginDate());
        lqw.eq(bo.getEndDate() != null, TiktokActivity::getEndDate, bo.getEndDate());
        lqw.eq(StringUtils.isNotBlank(bo.getActityType()), TiktokActivity::getActityType, bo.getActityType());
        lqw.eq(bo.getShopId() != null, TiktokActivity::getShopId, bo.getShopId());
        lqw.like(bo.getShopName() != null, TiktokActivity::getShopName, bo.getShopName());
        lqw.eq(bo.getStatus() != null, TiktokActivity::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getVideoTitle()), TiktokActivity::getVideoTitle, bo.getVideoTitle());
        return lqw;
    }
}
